/**
 * Object for four clics management
 * @author Christian DRAMSY, OCCELLO Alexandre
 */
var FOUR_CLICS = {
    
    /**
     *  The URL that return a product information
     */
    sz_getProductInformationURL: "index.php?action=getProductInformationAction",
    /**
     *  The URL that return all axed product information
     */
    sz_getAxedProductInformationURL: "index.php?action=getAxedProductInformationAction",
    /**
     *  The URL that saves the product informations into the database
     */
    sz_saveProductInformationsIntoDatabaseURL: "index.php?action=saveProductInformationsIntoDatabase",
	
    dataStorageManagement : null,
    
    sz_ProductKeyInLocalStorage: "FourClicksProductList",
    /**
     *  The Current Coords of the barycentre. Tis array will be under the following form:
     *  "Axis1 {
     *      id_axis:
     *      Value: <the value: a1+a2+a3>,
     *      coord: <the barycentre calculated>
     *  },Axis2 {
     *      id_axis:
     *      Value: <the value: a1+a2+a3>,
     *      coord: <the barycentre calculated>
     *  }"
     *  
     *  Note : The standard axis has the same value and coord.
     */
    a_o_BarycentreCoords : new Array(),
    
    /**
     *  All selected Products are stored in this array
     */
    a_o_SelectedProductInformations: new Array(),
    
    /**
     *  Informations of all products ( Filled gradually )
     */
    a_o_AllProductInformations: new Array(),
    
    attributeInitialization: function() {
        FOUR_CLICS.dataStorageManagement = new DataStorageManagement();
        FOUR_CLICS.dataStorageManagement.create("l");
        FOUR_CLICS.dataStorageManagement.remove(FOUR_CLICS.sz_ProductKeyInLocalStorage);
		  
        //	Get all axed product informations
        jQuery.ajax({
            url: FOUR_CLICS.sz_getAxedProductInformationURL,
            data: {},
            dataType: 'json',
            beforeSend: function() {
                    
            },
            success: function(the_sz_StringifiedAxedProdcutInformations) {
                //  Get the data of the product clicked
                var a_o_ProductInformationToSave = the_sz_StringifiedAxedProdcutInformations;
                if(typeof(the_sz_StringifiedAxedProdcutInformations) != "object") {
                    a_o_ProductInformationToSave = JSON.parse(the_sz_StringifiedAxedProdcutInformations);
                }
                FOUR_CLICS.a_o_AllProductInformations = a_o_ProductInformationToSave;
            }
        });
    },
    
    /**
     * Method called when page is loaded and ready
     * @author Christian DRAMSY
     */
    init: function() {
        //  Initialize attributes
        FOUR_CLICS.attributeInitialization();
        //        jQuery(".product").mouseover(function() {
        //            //  Dom Id is get the format "product-<The product Id>"
        //            var sz_DomId = jQuery(this).attr("id");
        //            var a_DomIdSplitted = sz_DomId.split("-");
        //            var i_ProductId = a_DomIdSplitted[1];
        //            jQuery("#product-"+i_ProductId+"-informations").fadeIn();
        //        });
        //                
        //        jQuery(".product").mouseout(function() {
        //            //Dom Id is get the format "product-<The product Id>"
        //            var sz_DomId = jQuery(this).attr("id");
        //            var a_DomIdSplitted = sz_DomId.split("-");
        //            var i_ProductId = a_DomIdSplitted[1];
        //            jQuery("#product-"+i_ProductId+"-informations").fadeOut();
        //        });
        $("body").delegate(".product", "click", function() {
            
            //  Dom Id is get the format "product-<The product Id>"
            var sz_DomId = jQuery(this).attr("id");
            var a_DomIdSplitted = sz_DomId.split("-");
            var i_ProductId = a_DomIdSplitted[1];
            var o_DomProduct = jQuery(this);
            
            //  The product is already selected
            if(typeof(FOUR_CLICS.a_o_SelectedProductInformations[i_ProductId]) != "undefined") {
                FOUR_CLICS.displayProductInformations(i_ProductId);
                return false;
            }
            
            jQuery.ajax({
                url: FOUR_CLICS.sz_getProductInformationURL,
                data: {
                    product_id: i_ProductId
                },
                dataType: 'json',
                beforeSend: function() {
                    
                },
                success: function(the_sz_StringifiedProdcutInformations) {
                    //  Save the data only if the product isn't already saved
                    var o_ProductInformation = FOUR_CLICS.saveProduct(the_sz_StringifiedProdcutInformations);
                    //  Update the barycentre
                    FOUR_CLICS.updateBarycentre(the_sz_StringifiedProdcutInformations);
                    
                    //  If the product is a flaoting product we put the axis informations from barycentre to the product
                    if(o_ProductInformation.o_Product.status == 0) {
                        FOUR_CLICS.putBarycentreValueIntoProductAxis(o_ProductInformation);
                        FOUR_CLICS.saveProductIntoDatabase(o_ProductInformation);
                    }
                    
                    //  Suggest product after 4 clics
                    if(FOUR_CLICS.a_getSelectedProduct().length >= 4) {
                        var o_SuggestedProduct = FOUR_CLICS.getSuggestedProduct();
                        
						$("#suggested-product").empty();
                        if(o_SuggestedProduct) {
							$("#suggested-product").append("<h4>&bull; PRODUIT SUGGÉRÉ &bull;</h4><div id='productSidebar-"+o_SuggestedProduct.o_Product.id+"' class='product'><div style='margin: auto'><div class='product-title'>"+o_SuggestedProduct.o_Product.name+"</div><img alt='' src='images/products/"+o_SuggestedProduct.o_Product.picture+"' class='thumbSidebar' style='width:200px; height:200px;' /><br/></div></div>");
						}
						else {
							$("#suggested-product").append("<h4>&bull; PRODUIT SUGGÉRÉ &bull;</h4><div class='product'><div class='product-title'>Pas de produit suggéré !</div></div>");
						}
						$(".thumbSidebar").thumbs();
                    }
                    
                    //  Show the product informations
                    FOUR_CLICS.displayProductInformations(o_ProductInformation.o_Product.id);
                    if(o_DomProduct.attr("id") == ("productSidebar-"+o_ProductInformation.o_Product.id)) {
						$("#product-"+o_ProductInformation.o_Product.id).addClass("selectedProduct");
					}

                    o_DomProduct.addClass("selectedProduct");
                }
            });
            return true;
        });
    },
    /**
     *	Save the products informations (axis) into the database 
     */
    saveProductIntoDatabase: function(the_o_ProductInformation) {
		//	Get all axed product informations
        jQuery.ajax({
            url: FOUR_CLICS.sz_saveProductInformationsIntoDatabaseURL,
            data: {
				i_ProductId: the_o_ProductInformation.o_Product.id,
				o_ProductInformationAxis: the_o_ProductInformation.o_Axis
            },
            dataType: 'json',
            beforeSend: function() {
                    
            },
            success: function() {
                console.log("-- sauvegarde des infos du produit --");
            }
        });
	},
    /**
     * Put the data in localstorage
     * @author Christian DRAMSY
     */
    saveProduct: function(the_sz_StringifiedData) {
        if(typeof(the_sz_StringifiedData) == "undefined") {
            return false;
        }
        //  Get the data of the product clicked
        var o_ProductInformationToSave = the_sz_StringifiedData;
        if(typeof(the_sz_StringifiedData) != "object") {
            o_ProductInformationToSave = JSON.parse(the_sz_StringifiedData);
        }
        
        //  The product is already selected
        if(typeof(FOUR_CLICS.a_o_SelectedProductInformations[o_ProductInformationToSave.o_Product.id]) != "undefined") {
            return false;
        }
        
        //  If the axis value of the product is empty. Set the value to the barycentre value
        if(o_ProductInformationToSave.o_Axis.length==0) {
            FOUR_CLICS.updateBarycentre(o_ProductInformationToSave);
        }
        
        //  Save the selected product
        FOUR_CLICS.a_o_SelectedProductInformations[o_ProductInformationToSave.o_Product.id] = o_ProductInformationToSave;
        FOUR_CLICS.a_o_AllProductInformations[o_ProductInformationToSave.o_Product.id] = o_ProductInformationToSave;
        
        //  Get the array of product clicked in locaStorage
        var a_o_productList = FOUR_CLICS.a_getProductListFromLocalStorage();
        if(a_o_productList == false || a_o_productList == null) {
            a_o_productList = new Array();
        }
        
        a_o_productList[a_o_productList.length] = o_ProductInformationToSave.o_Product.id;
        //  Store to localStorage
        FOUR_CLICS.dataStorageManagement.store(FOUR_CLICS.sz_ProductKeyInLocalStorage,JSON.stringify(a_o_productList));
		
        // Display the number of selected products in the shopping cart
        var i_selectedProducts = FOUR_CLICS.a_getProductListFromLocalStorage().length;
        $('#number').empty().append(i_selectedProducts);
		
        return o_ProductInformationToSave;
    },
    /**
     * Return the product list from localStorage
     */
    a_getProductListFromLocalStorage: function() {
        var sz_StringifiedProductList = FOUR_CLICS.dataStorageManagement.getData(FOUR_CLICS.sz_ProductKeyInLocalStorage);
        var a_o_productList = JSON.parse(sz_StringifiedProductList);
        return a_o_productList;
    },
    /**
     *  The axis value from barycentre to the product informations
     */
    putBarycentreValueIntoProductAxis: function(the_o_productInformations) {
		the_o_productInformations.o_Axis = new Array();
        jQuery.each(FOUR_CLICS.a_o_BarycentreCoords,function(i_key, o_informations) {
            if(typeof(o_informations) != "undefined") {
//				console.log("i_axisId = "+o_informations.i_axisId+" -- f_coord = "+o_informations.f_coord);
				
                var o_Axis = new Object();
                o_Axis.id_axis = o_informations.i_axisId;
                o_Axis.value = o_informations.f_coord;
                the_o_productInformations.o_Axis[the_o_productInformations.o_Axis.length] = o_Axis;
            }
        }); 
        
        //  Save the product
        FOUR_CLICS.a_o_SelectedProductInformations[the_o_productInformations.o_Product.id] = the_o_productInformations;
        FOUR_CLICS.a_o_AllProductInformations[the_o_productInformations.o_Product.id] = the_o_productInformations;
    // TODO : Requete ajax pour l'enregistrement dans la base de données.
    },
    /**
     * Update the value of the barycentre if a product is clicked
     */
    updateBarycentre: function(the_sz_StringifiedData) {
        if(typeof(the_sz_StringifiedData) == "undefined") {
            return false;
        }
        //  Get the data of the product clicked
        var o_ProductInformationToSave = the_sz_StringifiedData;
        if(typeof(the_sz_StringifiedData) != "object") {
            o_ProductInformationToSave = JSON.parse(the_sz_StringifiedData);
        }
        var b_barycentreAlreadyFilled = false;
        jQuery.each(o_ProductInformationToSave.o_Axis,function(i_key,o_Axis) {
            //  There is not yet barycentre 
            if(typeof(FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis]) == "undefined" ) {
                var o_values = new Object();
                o_values.f_value = parseInt(o_Axis.value);
                o_values.f_coord = parseInt(o_Axis.value);
                o_values.i_axisId = parseInt(o_Axis.id_axis);
                //  Value and Coord are the same
                FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis]=o_values;
            } else {
                b_barycentreAlreadyFilled = true;
                //  For the coord we need a barycentre calculation
                var i_value = parseInt(o_Axis.value);
                var f_numerator = 
                i_value * i_value + FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis].f_value * FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis].f_coord;
                var f_denominator = FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis].f_value + i_value;
                //  Value is the current barycentre value + the axis value;
                FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis].f_value = 
                parseInt(o_Axis.value) + FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis].f_value;
                
                //  Coord
                if(f_denominator != 0) {
                    FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis].f_coord = parseInt(f_numerator/f_denominator);
                }else {
                    FOUR_CLICS.a_o_BarycentreCoords[o_Axis.id_axis].f_coord = 0;
                }
            }
        });
            
        //  If barycentre not yet filled, put the barycentre value to 
        if(!b_barycentreAlreadyFilled) {
/*            jQuery.each(FOUR_CLICS.a_o_SelectedProductInformations,function(i_key, o_Product) {
                if(typeof(o_Product) != "undefined") {
                    FOUR_CLICS.putBarycentreValueIntoProductAxis(FOUR_CLICS.a_o_SelectedProductInformations[i_key]);
                } 
            });
*/
        }
        
        FOUR_CLICS.displayBarycentre();
        
        return true;
    },
    /**
     * Display the barycentre on the page
     */
    displayBarycentre: function() {
        jQuery.each(FOUR_CLICS.a_o_BarycentreCoords,function(i_axisId, o_values){
            if(typeof(o_values) != "undefined") {
                jQuery("#axisValue-"+o_values.i_axisId).html(o_values.f_coord);
            }
        });
    },
    /**
     * Display the barycentre on the page
     */
    displayProductInformations: function(the_i_productId) {
        jQuery("#productTitle").html(FOUR_CLICS.a_o_AllProductInformations[the_i_productId].o_Product.name);
        jQuery.each(FOUR_CLICS.a_o_AllProductInformations[the_i_productId].o_Axis,function(i_key, o_Axis){
            if(typeof(o_Axis) != "undefined") {
                jQuery("#ProductAxisValue-"+o_Axis.id_axis).html(o_Axis.value);
            }
        });
    },
    /**
     * Get selected products
     */
    a_getSelectedProduct: function() {
        var a_SelectedProduct = new Array();
        jQuery.each(FOUR_CLICS.a_o_SelectedProductInformations,function(i_key, o_Product) {
            if(typeof(o_Product) != "undefined") {
                a_SelectedProduct.push(o_Product);
            } 
        });
        return a_SelectedProduct;
    },
    /**
     * Suggest a product according to the Selected products
     */
    getSuggestedProduct: function() {
        var f_barycentreOfTheBarycentre = 0;
        var f_barycentreNumerator = 0;
        var f_barycentreDenominator = 0;
        var f_absClosesProductBarycentre = 999999999;
        var o_ProductToSuggest = null;
        
        //  1. Calculate the barycentre of the barycentre
        //  ---------------------------------------------
        jQuery.each(FOUR_CLICS.a_o_BarycentreCoords,function(i_key, o_Values) {
            if(typeof(o_Values) != "undefined") {
                f_barycentreNumerator += o_Values.f_value * o_Values.f_coord;
                f_barycentreDenominator += o_Values.f_value;
            }
        });
        
        if(f_barycentreDenominator > 0) {
            f_barycentreOfTheBarycentre = f_barycentreNumerator / f_barycentreDenominator;
        }
        if(f_barycentreOfTheBarycentre == 0) {
            return false;
        }
        
        //  2. Calculate the closest product
        //  --------------------------------
        jQuery.each(FOUR_CLICS.a_o_AllProductInformations,function(i_key, o_ProductInformations) {
            var f_numerator = 0;
            var f_denominator = 0;
            var f_barycentre = 0;
            if(typeof(o_ProductInformations) != "undefined") {
                console.log("Not undefined "+o_ProductInformations.o_Product.name);
                //  Product not yet selected
                if(typeof(FOUR_CLICS.a_o_SelectedProductInformations[o_ProductInformations.o_Product.id]) == "undefined") {
                    console.log("Not yet saved "+o_ProductInformations.o_Product.name);
                    jQuery.each(o_ProductInformations.o_Axis,function(i_key, o_Axis) {
                        if(typeof(o_Axis) != "undefined") {
                            f_numerator += parseInt(o_Axis.value) * parseInt(o_Axis.value);
                            f_denominator += parseInt(o_Axis.value);
                        }
                    });
                    if(f_denominator > 0) {
                        console.log("denominator "+f_denominator);
                        f_barycentre = f_numerator / f_denominator;
                        //  Select the product to suggest
                        if(Math.abs(f_barycentreOfTheBarycentre - f_barycentre) < f_absClosesProductBarycentre) {
                            f_absClosesProductBarycentre = Math.abs(f_barycentreOfTheBarycentre - f_barycentre);
                            o_ProductToSuggest = o_ProductInformations;
                        }
                    }
                }
            }
        });
        
        console.log("Product To suggest : ");
        console.log(o_ProductToSuggest);
        
        return o_ProductToSuggest;
    },
    /**
 * Get barycentre from axis lists
 */
    f_getBarycentre: function(a_o_AxisList) {
        
    }
}
